﻿using PLCS.Domain.Logs;
using PLCS.Domain.Orders;
using PLCS.Domain.Shared.Processes;
using PLCS.Domain.Shared.Tasks;
using PLCS.Domain.Tasks;
using PLCS.EquipmentService.Models;
using PLCS.SocialHttpClient.WMS;
using PLCS.SocialHttpClient.WMS.Models;

using Volo.Abp.Domain.Repositories;

namespace PLCS.Web.EventHandlers.TaskFinshed
{
    public class TaskFinshDisposeOrderEventHandler : ILocalEventHandler<TaskFinshEvent>, ITransientDependency
    {
        private readonly ITaskRepository _taskRepository;
        private readonly IOrderRepository _orderRepository;
        private readonly IRepository<OrderRunningCondition> _orderRunningConditionRepository;
        private readonly WMSSocialService _wMSSocialService;
        private readonly ErrorLogManager _errorLogManager;

        public TaskFinshDisposeOrderEventHandler(ITaskRepository taskRepo, IOrderRepository orderRepository, IRepository<OrderRunningCondition> orderRunningConditionRepository, WMSSocialService wMSSocialService, ErrorLogManager errorLogManager)
        {
            _taskRepository = taskRepo;
            _orderRepository = orderRepository;
            _orderRunningConditionRepository = orderRunningConditionRepository;
            _wMSSocialService = wMSSocialService;
            _errorLogManager = errorLogManager;
        }

        public async Task HandleEventAsync(TaskFinshEvent eventData)
        {
            if (eventData.TaskSource == "WMS下发")
            {
                var result = await _wMSSocialService.ReportTaskAsync(eventData.TaskId_Higher, 2);
                if (result.Header.Code == "E")
                {
                    await _errorLogManager.AddErrorLogAsync(new ErrorLog("WMS", $"任务报工失败：{result.Header.Message}", "WMS接口调用", "通讯"));
                    GlobalModel.FailTaskIds.Add(new FailTask()
                    {
                        TaskId = eventData.TaskId_Higher
                    });
                }
            }

            if (string.IsNullOrWhiteSpace(eventData.OrderNo))
            {
                return;
            }

            #region 将工序情况置为执行完成

            // 找到当前工序下这个工单下的所有未完成的任务，如果为空，说明这个工序都做完了。
            var tasks = await _taskRepository.GetListAsync(x => x.OrderNo == eventData.OrderNo);

            if (tasks.Count == 1)
            {
                // 找到这个任务的工单
                var order = await _orderRepository.GetAsync(x => x.OrderNo == eventData.OrderNo);

                // 找到这个工单下当前执行的工序完成情况,并将其置为执行完成
                var orderRunningCondition = await _orderRunningConditionRepository.GetAsync(x => x.OrderNo == order.OrderNo && x.ProcessStatus == ProcessStatus.执行中);
                orderRunningCondition.ChangeStatus(ProcessStatus.已完成);
                await _orderRunningConditionRepository.UpdateAsync(orderRunningCondition);

                // 如果这是下线，那么将工单置为执行完成
                if (orderRunningCondition.IsEnd == Domain.Shared.Enums.YesNo.是)
                    await _orderRepository.ChangeOrderStatusAsync(order.OrderNo, Domain.Shared.Enums.OrderStatus.执行完成);
            }

            #endregion 将工序情况置为执行完成
        }
    }
}